package com.learn.controller;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/01/25
 * @description
 */
@Controller
// 表示需要存到session域的数据，指定键名
@SessionAttributes({"x", "y"})
public class SessionController {
    @RequestMapping("/session01")
    public String session01(HttpSession session) {
        session.setAttribute("username", "李四");
        return "ok";
    }

    @RequestMapping("/session02")
    public String session02(Model model) {
        // 这里虽然是调model的方法，但是确实存到了session中
        model.addAttribute("x", "xxx");
        model.addAttribute("y", "yyy");
        return "ok";
    }

    @RequestMapping("/app")
    public String app(HttpServletRequest request) {
        // request对象和session对象都可以获取ServletContext对象
        ServletContext application = request.getServletContext();
        application.setAttribute("username", "王五");
        return "ok";
    }
}
